package springboot.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springboot.Tools.Date.Month;
import springboot.Tools.Date.StartAndEndTime;
import springboot.Tools.Date.Week;
import springboot.Tools.HttpApi;
import springboot.doMain.*;
import springboot.service.impl.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
public class wxManager {
	
	final
	OverTimeDataServiceImpl overTimeDataService;
	final
	MsgServiceImpl msgService;
	final
	EngineerServiceImpl engineerService;
	final
	TbProblemStatusServiceImpl tbProblemStatusService;
	final StaffServiceImpl staffService;
	
	final
	OverTimeProServiceImpl overTimeProService;
	final
	OverTimeMsgServiceImpl overTimeMsgService;
	
	HttpApi httpApi = new HttpApi();
	
	public wxManager(MsgServiceImpl msgService,
	                 EngineerServiceImpl engineerService,
	                 TbProblemStatusServiceImpl tbProblemStatusService,
	                 StaffServiceImpl staffService,
	                 OverTimeProServiceImpl overTimeProService,
	                 OverTimeMsgServiceImpl overTimeMsgService, OverTimeDataServiceImpl overTimeDataService) {
		this.msgService = msgService;
		this.engineerService = engineerService;
		this.tbProblemStatusService = tbProblemStatusService;
		this.staffService = staffService;
		this.overTimeProService = overTimeProService;
		this.overTimeMsgService = overTimeMsgService;
		this.overTimeDataService = overTimeDataService;
	}
	
	
	@RequestMapping("/login")
	public String login(String username, String password, Model model) {
		
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
		try {//登录成功
			subject.login(usernamePasswordToken);
			
			return "redirect:/";
		} catch (UnknownAccountException e) {//用户名不存在
			model.addAttribute("msg", "用户名不存在");
			return "pages/samples/login";
		} catch (IncorrectCredentialsException b) {//密码错误
			model.addAttribute("msg", "密码错误");
			return "pages/samples/login";
		}
	}
	
	@RequestMapping("/")
	public String index(Model model) {
		
		//获取当前的Subject
		Subject currentUser = SecurityUtils.getSubject();
		//测试当前用户是否已经被认证(即是否已经登录)
		if (!currentUser.isAuthenticated() || currentUser.isRemembered()) {
			try {
				Staff staff = (Staff) currentUser.getPrincipal(); // 获取当前登录用户
				
				model.addAttribute("engineerName", staff.getName());
			} catch (Exception e) {
				System.err.println("未登录 = " + e);
			}
			model.addAttribute("all_engineer", staffService.sel_all_engineer());
		}
		
		return "index";
	}
	
	@RequestMapping("/logout")
	public String logout(Model model) {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		model.addAttribute("msg", "安全退出！");
		
		return "redirect:/login";
	}
	
	@RequestMapping("/manager1")
	public String manager1() {
		
		return "manager1";
	}
	
	@RequestMapping("/common")
	public String common() {
		
		return "common";
	}
	
	@RequestMapping("/manager")
	public String manager(Model model) {
		model.addAttribute("all_engineer", staffService.sel_all_engineer());
		return "manager";
	}
	
	
	//    获取部门人员的平均响应时间与回复数量
//    GET http://localhost:8080/engineerAvgTime?dataOption={"optionCode":"period","year":"0","month":"0","day":"0","period":"month"}
	@ResponseBody
	@GetMapping("/engineerAvgTime")
	public Map<String, Object> engineerAvgTime(String dataOption) {
		String optionCode = null;
		Date startTime;
		Date endTime;
		String period = null;
//        int year;
		int month;
		int week;
		int weekCount = 0;
		weekCount = StartAndEndTime.getWeekCount(weekCount);
		Map<String, Date> data = new HashMap<>();
		Map<String, Object> listMap = new HashMap<>();
		Month month2 = StartAndEndTime.getMonth(0);
		startTime = month2.getMonthStartTime();
		endTime = month2.getMonthEndTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if (dataOption != null) {
			JSONObject jsonObject = JSON.parseObject(dataOption);
			try {
				optionCode = jsonObject.getString("optionCode");
				if (optionCode != null) {
					switch (optionCode) {
						case "allData":
							startTime = sdf.parse(jsonObject.getString("startTime"));
							endTime = sdf.parse(jsonObject.getString("endTime"));
							if (startTime == null || endTime == null) {
								startTime = month2.getMonthStartTime();
								endTime = month2.getMonthEndTime();
							}
							break;
						case "period":
//                            year = (int) jsonObject.get("year");
							month = jsonObject.getInteger("month");
							week = jsonObject.getInteger("week");
							weekCount = StartAndEndTime.getWeekCount(month);
							
							Month month1 = StartAndEndTime.getMonth(month);
							period = jsonObject.getString("period");
							if (period != null) {
								if (period.equals("week")) {
									Week week1 = StartAndEndTime.getWeek(month, week);
									startTime = week1.getWeekStartTime();
									endTime = week1.getWeekEndTime();
								} else if (period.equals("month")) {
									startTime = month1.getMonthStartTime();
									endTime = month1.getMonthEndTime();
								} else {
									return null;
								}
							}
							break;
						default:
							return null;
					}
				}
			} catch (Exception e) {
				System.err.println("e = " + e);
				return null;
			}
		}
		
		data.put("startTime", startTime);
		data.put("endTime", endTime);
//		listMap.put("groupData", WXWorkApi.getWeekData(startTime, endTime));
		List<Map<Object, Object>> maps = msgService.engineerData(data);
		
		
		listMap.put("data", maps);
		listMap.put("weekCount", weekCount);
		listMap.put("startTime", sdf.format(startTime));
		listMap.put("endTime", sdf.format(endTime));
		listMap.put("optionCode", optionCode == null ? "null" : optionCode);
		listMap.put("period", period == null ? "null" : period);
		
		return listMap;
	}
	
	@ResponseBody
	@GetMapping("/del_pro_status")
	public int del_pro_status(int idProblemStatus) {
		if (idProblemStatus == 0) {
			return 0;
		}
		return tbProblemStatusService.del_pro_status(idProblemStatus);
	}
	
	//通过问题id查询问题状态
	@ResponseBody
	@GetMapping("/problemStatusByHq")
	public List<TbProblemStatus> problemStatusByHq(int hq) {
		return tbProblemStatusService.problemStatusByHq(hq);
	}
	
	//    需要添加问题状态的数量
	@ResponseBody
	@GetMapping("/needAddProStatusNum")
	List<Map<String, Object>> selEngineerNeedAddProblemStatusCount() {
		return tbProblemStatusService.selEngineerNeedAddProblemStatusCount();
	}
	
	//需要回复的消息数量
	@ResponseBody
	@GetMapping("/needToReplyNum")
	List<Map<String, Object>> selEngineerNeedToReplyNum() {
		return tbProblemStatusService.selEngineerNeedToReplyNum();
	}
	
	
	//历史超时数据
	@ResponseBody
	@GetMapping("/selLastDataNum")
	List<Map<String, Object>> selLastDataNum() {
		return tbProblemStatusService.selEngineerNeedToReplyNum();
	}
	
	
	//向数据库插入数据
	@ResponseBody
	@GetMapping("/insertEveryDayData")
	boolean test() {
		overTimeDataService.insertOverTimeData();
		OverTimePro overTimePro = new OverTimePro(httpApi.address("needToReplyNum"));
		OverTimeMsg overTimeMsg = new OverTimeMsg(httpApi.address("needAddProStatusNum"));
		try {
			overTimeMsgService.insert(overTimeMsg);
			overTimeProService.insert(overTimePro);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	
	@ResponseBody
	@GetMapping("/selEngineerWorkInfo")
	List<Map<String, Object>> selEngineerWorkInfo(Map<String, Object> objectMap) {
		return msgService.selEngineerWorkInfo(objectMap);
	}
	
	
	@ResponseBody
	@GetMapping("/sameYesterday")
	int sameYesterday(String data) {
		Staff staff = (Staff) SecurityUtils.getSubject().getPrincipal(); // 获取当前登录用户
		if (staff == null || data == null) {
			return 0;
		}
		JSONObject jsonObject = JSON.parseObject(data);
		TbProblemStatus msgStatusContentValue = tbProblemStatusService.lastStatus(jsonObject.getInteger("hq"));
		/*如果之前没有记录,则直接退出*/
		if (msgStatusContentValue == null) {
			return 0;
		}
		msgStatusContentValue.setEngineer(staff.getName());
		if (msgStatusContentValue.getStatusContent() == null
				|| msgStatusContentValue.getEngineer() == null
				|| msgStatusContentValue.getHq() == null) {
			return 0;
		}
		tbProblemStatusService.insertProblemStatusContent(msgStatusContentValue);
		return 1;
	}
	
	
	@ResponseBody
	@GetMapping("add_problem_status")
	public int add_problem_status(String data) {
		if (data == null) {
			return 0;
		}
		JSONObject jsonObject = JSON.parseObject(data);
		Msg msg = new Msg();
		TbProblemStatus tbProblemStatus = new TbProblemStatus();
		tbProblemStatus.setStatusContent(jsonObject.getString("msgStatusContentValue"));
		
		Staff staff = (Staff) SecurityUtils.getSubject().getPrincipal(); // 获取当前登录用户
		tbProblemStatus.setEngineer(staff.getName());
		tbProblemStatus.setHq(jsonObject.getInteger("hq"));
		
		msg.setHq(jsonObject.getInteger("hq"));
		String nowDate = new SimpleDateFormat("yy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis()));
		
		jsonObject.fluentPut("time", nowDate);
		
		jsonObject.fluentPut("engineer", null);
		
		msg.setMsgStatus("<tr><td>" + jsonObject.getString("msgStatusContentValue") + "</td><td>" + nowDate + "</td><td>" + "null" + "</td></tr>");
		
		int code_add_problem_status = msgService.add_problem_status(msg);
		int code_insertProblemStatusContent = tbProblemStatusService.insertProblemStatusContent(tbProblemStatus);
		
		if (code_add_problem_status == code_insertProblemStatusContent && code_add_problem_status == 0) {
			return 0;
		} else {
			return 1;
		}
		
	}
	
	@ResponseBody
	@GetMapping("change_problem")
	public int change_problem(String data) {
		Msg msg = new Msg();
		JSONObject jsonObject = JSON.parseObject(data);
		
		msg.setHq(jsonObject.getInteger("hq"));
		msg.setText(jsonObject.getString("text"));
		return msgService.change_problem(msg);
	}
	
}
